import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

/**
 * @author create on 2021/7/9
 */
public class PathChildrenCacheExample {
    static String path = "/zkTest/parentChildCache";
    static String connIp = "127.0.0.1";
    static CuratorFramework client = CuratorFrameworkFactory.builder().connectString(connIp)
            .sessionTimeoutMs(60 * 1000)
            .connectionTimeoutMs(15 * 1000)
            .retryPolicy(new ExponentialBackoffRetry(1000, 3,Integer.MAX_VALUE))
            .build();

    public static void main(String[] args)  throws Exception {
        client.start();
//        client.delete().forPath(path);


        /**
         * PathChildrenCache 用来监听子节点的变化，子节点数据发生改变的时候就会触发监听。
         * event.getType 对应各个子节点的变化类型。
         * 同理还有 {@link TreeCache }
         */
        final PathChildrenCache pathChildrenCache = new PathChildrenCache(client, path, true);
        pathChildrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
        pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {

            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                switch (event.getType()){
                    case CHILD_ADDED:
                        System.out.println(" child Added : " + new String(event.getData().getData() )+ "path:" + event.getData().getPath());
                    case CHILD_UPDATED:
                        System.out.println(" child updated : " +  new String(event.getData().getData() ) + "path:" + event.getData().getPath());
                    case CHILD_REMOVED:
                        System.out.println(" child removed : " +  new String(event.getData().getData() ) + "path:" + event.getData().getPath());
                    case INITIALIZED:
                        System.out.println(" child INITIALIZED");
                    default:
                            break;
                }
            }
        });

//        client.delete().forPath(path);

        client.create().withMode(CreateMode.PERSISTENT).forPath(path , "init".getBytes());
        Thread.sleep(1000);
        client.create().withMode(CreateMode.PERSISTENT).forPath(path + "/childOne" , "init".getBytes());
        Thread.sleep(1000);
        client.setData().forPath(path + "/childOne" , "changeData".getBytes());
        Thread.sleep(1000);
        client.delete().forPath(path + "/childOne");
        Thread.sleep(1000);
        client.delete().forPath(path );
        pathChildrenCache.close();
        client.close();
    }
}
